package ruifight.member.config;

import com.fasterxml.jackson.databind.ObjectMapper;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import ruifight.member.model.UserInfo;
import ruifight.member.model.security.MyUserDetail;
import ruifight.member.util.JsonUtils;
import ruifight.member.util.MD5Util;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class JWTLoginFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;

    public JWTLoginFilter(AuthenticationManager authenticationManager) {
    	this.setFilterProcessesUrl("/interface/login");
        this.authenticationManager = authenticationManager;
    }

    // 接收并解析用户凭证
    @Override
    public Authentication attemptAuthentication(HttpServletRequest req,
                                                HttpServletResponse res) throws AuthenticationException {
        try {
            UserInfo userInfo = new ObjectMapper()
                    .readValue(req.getInputStream(), UserInfo.class);
            userInfo.setPassword(MD5Util.MD5(userInfo.getPassword()));
            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                    		userInfo.getLoginName(),
                    		userInfo)
            );
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    // 用户成功登录后，这个方法会被调用，我们在这个方法里生成token
    @Override
    protected void successfulAuthentication(HttpServletRequest req,
                                            HttpServletResponse res,
                                            FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {
    	MyUserDetail ud = (MyUserDetail) auth.getPrincipal();
    	Map<String, Object> claims=new HashMap<String, Object>();
    	claims.put("loginName", ud.getUsername());
    	claims.put("password", ud.getPwd());
        String token = Jwts.builder()
                .setClaims(claims)
//                .setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 24 * 1000))
                .signWith(SignatureAlgorithm.HS512, "ruifight")
                .compact();
        res.addHeader("Authorization", "Bearer " + token);
        Map<String, Object> retMap=new HashMap<String, Object>();
        retMap.put("state", 1);
        retMap.put("userType", ud.getUserType());
        retMap.put("userInfoId", ud.getUserInfoId());
        retMap.put("shopInfoId", ud.getShopInfoId());
        PrintWriter pw=res.getWriter();
        pw.print(JsonUtils.toJson(retMap));
        pw.flush();

    }

}
